package com.bardpub.weblite.ui 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	/**
	 * ...
	 * @author bardpub
	 */
	public class BitbltMovie extends Sprite
	{
		
		private var _data:BitmapData;
		private var _canvas:BitmapData;
		private var _totalFrame:int;
		private var _rowNum:int;
		private var _colNum:int;
		private var _currentFrame:int = 1;
		private var _rect:Rectangle;
		private var _w:Number;
		private var _h:Number;
		
		public function BitbltMovie(data:BitmapData, width:Number = 40, height:Number = 40, rowNum:int = 4, colNum:int = 5) 
		{
			_totalFrame = rowNum * colNum;
			_rowNum = rowNum;
			_colNum = colNum;
			_w = width;
			_h = height;
			_data = data;
			_canvas = new BitmapData(width, height, true, 0);
			addChild(new Bitmap(_canvas));
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			addEventListener(Event.REMOVED_FROM_STAGE, onRemoveFromStage);
		}
		
		private function onRemoveFromStage(e:Event):void 
		{
			removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
			
		}
		
		
		public function play():void 
		{
			addEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}
		
		public function stop():void 
		{
			removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}
		
		public function gotoAndPlay(frame:int):void 
		{
			_currentFrame = frame;
			addEventListener(Event.ENTER_FRAME, enterFrameHandler);
			
		}
		
		public function gotoAndStop(frame:int):void 
		{
			_currentFrame = frame;
			removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
		
			draw();
		}
		
		public function dispose():void
		{
			_canvas.dispose();
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			removeEventListener(Event.REMOVED_FROM_STAGE, onRemoveFromStage);
		}
		
		private function draw():void 
		{
			_rect = new Rectangle((_currentFrame-1) % _colNum * _w, int((_currentFrame-1) / _colNum) * _h,
								  _w, _h);
			_canvas.copyPixels(_data, _rect, new Point(0, 0));
		}
		
		private function enterFrameHandler(e:Event):void 
		{
			draw();
			_currentFrame++;
			if (_currentFrame > _totalFrame)
			{
				_currentFrame = 1;
			}
		}
		
		private function onAddedToStage(e:Event):void 
		{
			addEventListener(Event.ENTER_FRAME, enterFrameHandler);
			
			
		}
		
	}

}